// pages/createRoom/createRoom.js
import {$await,dateStr2timestamp} from '../../utils/util'
import {audioRoomAPI} from '../../api/audioRoom/index'
Page({

  /**
   * 页面的初始数据
   */
  data: {
    tip:false,// 提示
    notice:'',// 公告
    topic:'', // 话题
    createInfo:{ // 房间信息
      topic_end:'',
      topic_start:'',
      state:1
    },
    agree:false,
    hasTime:false
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {

  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
    
  },
  // 显示提示
  showTip(){
    this.setData({tip:!this.data.tip})
  },
  toWeb(){
    const url = 'https://h5.cbct.cn/html/hostserve_v2.html'
    wx.navigateTo({
      url:`/pages/webview/webview?webURL=${url}`
    })
  },
  // 房间参数校验
  validateInfo(){
    if(!this.data.topic){
      wx.showToast({
        icon:'none',
        title: '请填写房间话题',
        duration: 3000
      })
      return false
    }
    if(!this.data.agree){
      wx.showToast({
        icon:'none',
        title: '请勾选我已阅读协议',
        duration: 3000
      })
      return false
    }
    if(this.data.hasTime){
      const {topic_end,topic_start} = this.data.createInfo
      if(!topic_start || !topic_end){
        wx.showToast({
          icon:'none',
          title: '请设置开始结束时间',
          duration: 3000
        })
        return false
      } else {
        const start = dateStr2timestamp(topic_start)
        const end = dateStr2timestamp(topic_end)
        if(start > end){
          wx.showToast({
            icon:'none',
            title: '开始时间不能大于结束时间',
            duration: 3000
          })
          return false
        }
        if((end - start) < 1000*60*5){
          wx.showToast({
            icon:'none',
            title: '开始结束时间间隔需大于5分钟',
            duration: 3000
          })
          return false
        }
      }
    }
    return true
  },
  
  // 建房
  async createRoom(){
    if(!this.validateInfo()) return
    const {topic,notice,hasTime} = this.data
    const state = hasTime ? 1 : 2
    const params = {
      ...this.data.createInfo,
      notice,
      topic,
      state,
    }
    const [err,res] = await $await(audioRoomAPI.createRoom({...params}))
    if(res){
      const url = state === 2
       ? 
       `/pages/audioRoom/audioRoom?roomNumber=${res.room_number}`+'&from1=wxapp'
       :
       `/pages/salon/salon`
       wx.redirectTo({
        url,
      })
    }
  },
  // 时间是否选择
  toggleTime(){
    this.setData({
      hasTime:!this.data.hasTime,
      tip:false
    })
  },
  // 协议是否同意
  toggleAgree(){
    this.setData({agree:!this.data.agree})
  },
  // 选择开始时间
  startTimeChange(e){
    const {detail:{value:start}} = e
    const topic_start = 'createInfo.topic_start'
    this.setData({[topic_start]:start})
  },
  // 选择结束时间
  endTimeChange(e){
    const {detail:{value:end}} = e
    const topic_end = 'createInfo.topic_end'
    this.setData({[topic_end]:end})
  },
  
})